<template>
  <view class="content">
    <text class="title">高级API请求示例</text>
    
    <view class="section">
      <text class="section-title">用户管理</text>
      <button @click="fetchUsers" class="btn">获取用户列表</button>
      <button @click="createTestUser" class="btn">创建测试用户</button>
      <button @click="updateFirstUser" class="btn" :disabled="!firstUserId">更新第一个用户</button>
      <button @click="deleteLastUser" class="btn secondary" :disabled="!lastUserId">删除最后一个用户</button>
      
      <view v-if="loading" class="loading">
        <text>加载中...</text>
      </view>
      
      <view v-else class="user-list">
        <view 
          v-for="user in users" 
          :key="user.id" 
          class="user-item"
        >
          <text class="user-name">{{ user.name }}</text>
          <text class="user-email">{{ user.email }}</text>
          <view class="user-actions">
            <button @click.stop="fetchUserDetail(user.id)" class="btn-small">详情</button>
            <button @click.stop="deleteUser(user.id)" class="btn-small secondary">删除</button>
          </view>
        </view>
      </view>
    </view>
    
    <view class="section" v-if="userDetail.id">
      <text class="section-title">用户详情</text>
      <view class="user-detail">
        <text>ID: {{ userDetail.id }}</text>
        <text>姓名: {{ userDetail.name }}</text>
        <text>用户名: {{ userDetail.username }}</text>
        <text>邮箱: {{ userDetail.email }}</text>
        <text>电话: {{ userDetail.phone }}</text>
        <text>网站: {{ userDetail.website }}</text>
        <text>公司: {{ userDetail.company?.name }}</text>
        <text>地址: {{ userDetail.address?.city }}, {{ userDetail.address?.street }}</text>
      </view>
      <button @click="clearUserDetail" class="btn secondary">关闭详情</button>
    </view>
    
    <view class="section">
      <text class="section-title">错误处理测试</text>
      <button @click="test404Error" class="btn">测试404错误</button>
      <button @click="testNetworkError" class="btn">测试网络错误</button>
      <view v-if="errorInfo" class="error-info">
        <text>错误信息: {{ errorInfo }}</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import userApi from '../../api/user.js'

// 响应式数据
const users = ref([])
const userDetail = ref({})
const loading = ref(false)
const errorInfo = ref('')
const firstUserId = computed(() => users.value.length > 0 ? users.value[0].id : null)
const lastUserId = computed(() => users.value.length > 0 ? users.value[users.value.length - 1].id : null)

// 清除错误信息
const clearError = () => {
  errorInfo.value = ''
}

// 获取用户列表
const fetchUsers = async () => {
  clearError()
  loading.value = true
  const res = await userApi.getUserList()
  users.value = res
  loading.value = false
}

// 创建测试用户
const createTestUser = async () => {
  clearError()
  const userData = {
    name: '测试用户' + Date.now(),
    username: 'testuser' + Date.now(),
    email: 'test' + Date.now() + '@example.com'
  }
  
  const res = await userApi.createUser(userData)
  users.value.unshift(res)
}

// 更新第一个用户
const updateFirstUser = async () => {
  if (!firstUserId.value) return
  
  clearError()
  const updateData = {
    name: '更新用户' + Date.now(),
    email: 'updated' + Date.now() + '@example.com'
  }
  
  const res = await userApi.updateUser(firstUserId.value, updateData)
  
  // 更新本地数据
  const index = users.value.findIndex(user => user.id === firstUserId.value)
  if (index !== -1) {
    users.value[index] = { ...users.value[index], ...res }
  }
  
  // 如果详情页显示的是这个用户，也更新详情
  if (userDetail.value.id === firstUserId.value) {
    userDetail.value = { ...userDetail.value, ...res }
  }
}

// 删除用户
const deleteUser = async (id) => {
  clearError()
  await userApi.deleteUser(id)
  
  // 从列表中移除
  users.value = users.value.filter(user => user.id !== id)
  
  // 如果详情页显示的是这个用户，清空详情
  if (userDetail.value.id === id) {
    userDetail.value = {}
  }
}

// 删除最后一个用户
const deleteLastUser = async () => {
  if (!lastUserId.value) return
  await deleteUser(lastUserId.value)
}

// 获取用户详情
const fetchUserDetail = async (id) => {
  clearError()
  const res = await userApi.getUserById(id)
  userDetail.value = res
}

// 清空用户详情
const clearUserDetail = () => {
  userDetail.value = {}
}

// 测试404错误
const test404Error = async () => {
  clearError()
  try {
    await userApi.getUserById(999999) // 不存在的用户ID
  } catch (error) {
    errorInfo.value = `404错误: ${error.message || '用户不存在'}`
  }
}

// 测试网络错误
const testNetworkError = async () => {
  clearError()
  try {
    // 创建一个会超时的请求来模拟网络错误
    const controller = new AbortController()
    setTimeout(() => controller.abort(), 100) // 100ms后中止请求
    
    await fetch('https://httpstat.us/500', {
      signal: controller.signal
    })
  } catch (error) {
    errorInfo.value = `网络错误: ${error.message || '网络连接失败'}`
  }
}
</script>

<style>
.content {
  padding: 40rpx;
}

.title {
  font-size: 40rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 40rpx;
  display: block;
}

.section {
  margin-bottom: 60rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  display: block;
}

.btn {
  background-color: #007aff;
  color: white;
  border: none;
  padding: 20rpx;
  margin: 10rpx 0;
  border-radius: 10rpx;
  width: 100%;
}

.btn:disabled {
  background-color: #ccc;
}

.btn.secondary {
  background-color: #ff3b30;
}

.btn-small {
  background-color: #007aff;
  color: white;
  border: none;
  padding: 10rpx 15rpx;
  margin: 5rpx;
  border-radius: 5rpx;
  font-size: 24rpx;
}

.btn-small.secondary {
  background-color: #ff3b30;
}

.loading {
  text-align: center;
  padding: 40rpx 0;
}

.user-list {
  margin-top: 20rpx;
}

.user-item {
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
  background-color: #f8f8f8;
  margin-bottom: 10rpx;
  border-radius: 10rpx;
}

.user-name {
  font-weight: bold;
  font-size: 30rpx;
}

.user-email {
  color: #666;
  font-size: 26rpx;
  margin: 10rpx 0;
  display: block;
}

.user-actions {
  display: flex;
  justify-content: flex-end;
}

.user-detail {
  background-color: #f8f8f8;
  padding: 30rpx;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
}

.user-detail text {
  display: block;
  margin: 10rpx 0;
  font-size: 28rpx;
}

.error-info {
  background-color: #ffebee;
  color: #c62828;
  padding: 20rpx;
  border-radius: 10rpx;
  margin-top: 20rpx;
}
</style>